package routers

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/excelrept"
)

//OptionInfo 选项信息
type OptionInfo struct {
	RunID       int        `json:"runID"`
	Default     string     `json:"default"`
	List        []ListItem `json:"list"`
	CanUse      bool       `json:"canUse"`
	CanBack     bool       `json:"canBack"`
	CanApproval bool       `json:"canApproval"`
}

//ListItem 数据项
type ListItem struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

//GetReptDataRouter 获取报表数据路由
func GetReptDataRouter(c echo.Context) error {
	reptName := c.FormValue("reptName")
	if reptName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "form参数reptName不能为空！")
	}
	paramsStr := c.FormValue("params")
	if paramsStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "form参数params不能为空！")
	}
	conf, err := excelrept.GetConfig(reptName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var reqParams map[string]string
	err = json.Unmarshal([]byte(paramsStr), &reqParams)
	if err != nil {
		echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var params []excelrept.Parameter
	var paramMap map[string]string
	params, paramMap, err = initExcelReportParams(reptName, conf.Params, reqParams)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	reptInfo, err := getReptInfo(reptName, reqParams, claims.UserID)
	if err != nil {
		echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tpl, err := excelrept.GetPageData(reptName, paramMap, reptInfo)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	tpl.Params = params
	if paramsStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, err)
	}
	return c.JSON(http.StatusOK, tpl)
}

func initExcelReportParams(repName string, params []excelrept.Parameter, paramMap map[string]string) ([]excelrept.Parameter, map[string]string, error) {
	if paramMap == nil {
		paramMap = make(map[string]string, 5)
	}
	var dataType = base.AppConf.MainDataSource
	if dataType == "" {
		dataType = "EDW"
	}
	dataType = strings.ToUpper(dataType)
	if dataType != "ODS" && dataType != "EDW" {
		return nil, nil, fmt.Errorf("指定的数据源%s无效,必须是ODS或EDW", dataType)
	}
	if strings.HasPrefix(repName, "ods_") {
		dataType = "ODS"
	}
	plen := len(params)
	retPs := make([]excelrept.Parameter, plen)
	for i, param := range params {
		pv, ok := paramMap[param.Name]
		if ok {
			param.InitVal = pv
		} else {
			if initV, err := getInitValue(param.InitVal, dataType); err == nil {
				param.InitVal = initV
				paramMap[param.Name] = initV
			} else {
				return nil, nil, err
			}
		}
		retPs[i] = param
	}
	return retPs, paramMap, nil
}

//ExportReptRouter 导出报表路由
func ExportReptRouter(c echo.Context) error {
	reptName := c.FormValue("reptName")
	if reptName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "form参数reptName不能为空！")
	}
	paramsStr := c.FormValue("params")
	if paramsStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "form参数params不能为空！")
	}
	var params map[string]string
	err := json.Unmarshal([]byte(paramsStr), &params)
	if err != nil {
		echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	reptInfo, err := getReptInfo(reptName, params, claims.UserID)
	if err != nil {
		echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	buff, err := excelrept.Export(reptName, params, reptInfo)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	fileName := reptName + ".xlsx"
	fileName = base64.StdEncoding.EncodeToString([]byte(fileName))
	c.Response().Header().Set("Content-Type", "application/vnd.ms-excel")
	c.Response().Header().Set("Content-Disposition", fileName)
	return c.Blob(http.StatusOK, "application/vnd.ms-excel", buff.Bytes())
}

//getReptInfo 获取报表信息
func getReptInfo(reptName string, params map[string]string, uid int) (rInfo *excelrept.ReptInfo, err error) {
	rInfo = &excelrept.ReptInfo{
		TBSJ: params["TBSJ"],
	}
	return
}
